package model;

import com.ansj.vec.Word2VEC;
import entity.News;
import org.apache.log4j.Logger;
import utils.IOUtils;
import utils.SqlUtil;
import utils.VecModel;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by 梅晨 on 2017/7/20.
 */
public class Predict extends PreProcess {
    private static Logger logger = Logger.getLogger(Predict.class);
    private String testlibSVMPath;
    private String trainlibSVMPath;
    private String accuracyFilePath;

    public Predict(HashMap<String, Integer> filePathClaMap, String modelPath, String dicPath, String testlibSVMPath,String trainlibSVMPath,String accuracyFilePath) {
        super(filePathClaMap,modelPath,dicPath,testlibSVMPath);
        this.testlibSVMPath = testlibSVMPath;
        this.trainlibSVMPath = trainlibSVMPath;
        this.accuracyFilePath = accuracyFilePath;
    }

    public void run()throws IOException{
        List<News> newsList = newObj();
        logger.info("now loading veccmodel");
        VecModel vecModel = new VecModel(modelPath,dicPath);
        Word2VEC word2VEC = vecModel.loadModel();
        logger.info("process the word to wordvec");
        VecProcess(newsList,word2VEC);
        String modelFile = trainlibSVMPath + ".model";
        String[] testArgs = {testlibSVMPath, modelFile, accuracyFilePath};
        logger.info("start livbsvm predict");
        svm_predict.main(testArgs);
//        printErrorClass(newsList,accuracyFilePath);
//        SqlUtil sqlUtil = new SqlUtil();
//        sqlUtil.insert(newsList);
    }

    /**
     * 在控制台输出分错类的文件内容以及它的真是类别
     * @param newsList
     * @param accuracyFilePath
     * @throws IOException
     */
    private void printErrorClass(List<News> newsList, String accuracyFilePath)throws IOException{
        HashMap<Integer,String> map = new HashMap<Integer, String>();
        map.put(1,"正向");
        map.put(2,"负向");
        List<Integer> classList = IOUtils.readClassId(accuracyFilePath);
        if(newsList.size() == classList.size()){
            for(int i = 0; i < newsList.size(); i++){
                News news = newsList.get(i);
                if(news.getEmotionIndex() != classList.get(i)){
                    System.out.println(news.getContent());
                    System.out.println("真实类别为：" + map.get(news.getEmotionIndex()) + ";分类类别为：" + map.get(classList.get(i)));
                }
                news.setEmotionIndex(classList.get(i));//将默认的分类改为预测的分类结果
                if(news.getEmotionIndex() == 1){
                    news.setEmotion("正向");
                }else {
                    news.setEmotion("负向");
                }
            }
//            IOUtils.saveByClass(newsList,map,"result");
        }else {
            logger.error("分类文件与分类结果长度不一致");
        }
    }
}
